#-*-coding:utf-8-*-

from paramiko.rsakey import RSAKey
from paramiko import SSHException
import StringIO
import os, stat


def gen_keys(user, path):
    output = StringIO.StringIO()
    sbuffer = StringIO.StringIO()
    try:
        key = RSAKey.generate(2048)
        key.write_private_key(output)
        private_key = output.getvalue()
    except IOError:
        raise IOError('gen_keys: there was an error writing to the file')
    except SSHException:
        raise SSHException('gen_keys: the key is invalid')
    user = 'itadmin_' + user
    for data in [key.get_name(),
                 " ",
                 key.get_base64(),
                 " %s@%s" % (user, os.uname()[1])]:
        sbuffer.write(data)
    public_key = sbuffer.getvalue()
    f = open('%s/id_rsa.pub' % path, 'w')
    f.write(public_key)
    f.close()
    f = open('%s/id_rsa' % path, 'w')
    f.write(private_key)
    f.close()
    f = open('%s/.default_ids' % path, 'w')
    f.write('id_rsa')
    f.close()
    os.chmod('%s/id_rsa.pub' % path, stat.S_IREAD|stat.S_IWRITE)
    os.chmod('%s/id_rsa' % path, stat.S_IREAD|stat.S_IWRITE)
    os.chmod('%s/.default_ids' % path, stat.S_IREAD|stat.S_IWRITE)
